package com.hgw.rocketmqtemplatedemo.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

/**
 * Description: 监听事务
 *
 * @author LinHuiBa-YanAn
 * @date 2023/2/21 19:00
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQTransactionListener
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    /**
     * 执行本地事务逻辑
     *
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 模拟当key为偶数时提交事务，为基数UNKNOWN（在指定次数下检查当前事务状态）
        MessageHeaders headers = msg.getHeaders();
        //获取事务ID
        String transactionId = (String) headers.get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        String key = (String) headers.get(RocketMQHeaders.PREFIX + RocketMQHeaders.KEYS);
        log.info("执行本地事务,事务id:{},key:{}", transactionId, key);
        if (Integer.parseInt(key) % 2 == 0) {
            //执行成功，可以提交事务
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    /**
     * 检查事务状态
     *
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 模拟检查事务状态时回滚
        MessageHeaders headers = msg.getHeaders();
        String transactionId = (String) headers.get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        String key = (String) headers.get(RocketMQHeaders.PREFIX + RocketMQHeaders.KEYS);
        log.info("检查本地事务,事务id:{},key:{}", transactionId, key);
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
